/**
 * 高亮插件，GlightJS版，需依赖jQuery，会污染jQuery对象
 * Author: 陆楚良
 * Version: 1.0.0
 * Date: 2014/11/28
 * QQ: 519998338
 *
 * https://git.oschina.net/luchg/jquery.highlight.js.git
 *
 * GlightJS: https://git.oschina.net/luchg/Glight.js.git
 * License: http://www.apache.org/licenses/LICENSE-2.0
 **/
/*
用法：
define(function(require, base){
	var $ = require("jquery");
	require("jquery.highlight")($);
	$(".selector").highlight("classname", "href");
});
*/
GlightJS.define(function(){
	return function($){
		//className-高亮样式名，attrName-元素属性名(缺省href)
		$.fn.highlight = function(className, attrName){
			var attrName = attrName || "href";
			var self = this;
			var f = function(){
				var top = $(document).scrollTop();
				var bottom=$(document).scrollTop()+$(window).height();
				var list = [];
				self.each(function(){
					var h = $(this).attr(attrName);
					if(h==="#"){
						list.push({top:0, bottom:0});
					}
					else if(/^#.+/.test(h)){
						var o = $(h).offset();
						o= (typeof o == "object") ? o : {top:0};
						list.push({top:o.top, bottom:o.top+Number($(h).height())});
					}
				});
				self.removeClass(className);
				for(var i=0;i<list.length; i++){
					if(list[i].top>=top && list[i].top<=bottom && list[i].bottom<=bottom){//包含
						self.removeClass(className).eq(i).addClass(className);
						break;//第一个包含的内容以第一个为当前高亮
					}else{
						if(
							(list[i].top>=top && list[i].top<=bottom)// 露头
							|| (list[i].bottom>=top && list[i].bottom<=bottom)// 露尾
							|| (list[i].top<=top && list[i].bottom>=bottom)// 局部
						){
							self.removeClass(className).eq(i).addClass(className);
						}
					}
				}
			};
			$(window).scroll(f);
			f();
			return this;	/*return this使其可以连贯操作*/
		}
		return $;
	};
});